import React from 'react'

import { useEffect, useState } from 'react';

import { Card, Button, Tree, Table, Modal, Form, Input, Upload, message, Space, Popconfirm, Checkbox, Divider } from 'antd';
import { PlusOutlined, DeleteOutlined, FormOutlined, SyncOutlined, LoadingOutlined, InfoCircleOutlined, CheckOutlined, EditOutlined, UserOutlined, SearchOutlined } from '@ant-design/icons';
import { addRoleRes, getRoleListRes, deleteRoleRes, getAllTreeRes,setRoleTreeRes } from "@/api/v2/role";
import type { CheckboxChangeEvent } from 'antd/es/checkbox';
import type { CheckboxValueType } from 'antd/es/checkbox/Group';
import type { DataNode, TreeProps } from 'antd/es/tree';


let flag = false;
let flag1 = true;
export default function Role() {

  let [roleList, setRoleList] = useState<any>([]);
  let [total, setTotal] = useState(0);
  let [page, setPage] = useState(1);
  let [limit, setLimit] = useState(3);
  let [searchForm] = Form.useForm();
  let [addForm] = Form.useForm();
  let [editList, setEditList] = useState<any>([]);
  const [isModalOpen, setIsModalOpen] = useState(false);
  let [isOpen, setIsOpen] = useState(false);
  let [selectKeys, setSelectKeys] = useState([]);
  let [id, setId] = useState("");
  let [roleName, setRoleName] = useState("");
  const [treeData, setTreeData] = useState([]);

  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const [checkedKeys, setCheckedKeys] = useState<React.Key[]>([]);

  const [autoExpandParent, setAutoExpandParent] = useState<boolean>(true);
  let [show,setShow] = useState(0);



  useEffect(() => {

    getRoleList(page, limit);
    flag = false


  }, []);


  async function getRoleList(page: number, limit: number) {
    let result;
    if (flag) {
      let { search } = searchForm.getFieldsValue();
      console.log(search);

      result = await getRoleListRes(page, limit, search);
    } else {
      result = await getRoleListRes(page, limit, "");
    }


    setRoleList(result.items);
    setTotal(result.total);

  }

  function setTreeList(list: any) {
    return list.map((item: any) => {
      if (item.children && item.children.length) {
        item.children = setTreeList(item.children);
      }
      return {
        title: item.name,
        key: item.id,
        select: item.select,
        children: item.children
      }
    })
  }


  function setExpandKeys(list: any) {
    let arr: React.Key[] = [];
    fn(list);
    function fn(list: any) {
      list.forEach((item: any) => {
        if (item.children && item.children.length) {
          fn(item.children);
        }
        if (item.children && item.children.length) {
          arr.push(item.key);
          // console.log(item.key);

        }

      })

    }
    return arr;

  }

  function checkKeys(list: any) {
    let arr: React.Key[] = [];
    fn(list);
    function fn(list: any) {
      list.forEach((item: any) => {
        if (item.children && item.children.length) {
          fn(item.children);
        }
        if (item.select) {
          if (item.children && item.children.length) {

            let flag = item.children.every((item: any) => item.flag);
            if (flag) {
              arr.push(item.key);
            }
          }else{
            arr.push(item.key);
          }
        }

      })

    }
    return arr;
  }


  const columns: any = [
    {
      title: "序号",
      render: (txt: any, record: any, index: any) => {
        return index = 1
      },
      width: 80,
      align: "center"
    },
    {
      title: "角色名称",

      render: (data: any, record: any, index: number) => {
        return (
          <>
            {data.flag ? <div>
              <Input value={data.newName} onChange={(e) => {
                let list = [...roleList];
                list[index].newName = e.target.value;
                setRoleList(list);
              }}></Input>
              <Button type='primary' icon={<SyncOutlined />} onClick={() => {
                let list = [...roleList];
                list[index].newName = list[index].roleName;
                list[index].flag = false;
                setRoleList(list);
              }} style={{ background: "#e6a23c", borderColor: "#e6a23c" }}>取消</Button>
            </div> : <div>{data.roleName} </div>}
          </>
        )
      }

    },
    {
      title: "操作",
      render: (data: any, record: any, index: number) => {
        return (
          <>
            <Space>
              <Button type='primary' icon={<InfoCircleOutlined />} onClick={async () => {
                setId(data.id);
                setRoleName(data.roleName);
                let result = await getAllTreeRes(data.id);


                let list = setTreeList(result.children);
                let keys = setExpandKeys(list);
                let checks = checkKeys(list);
                console.log(list);
                setTreeData(list);
                setExpandedKeys(keys);
                console.log(keys, "key");
                setCheckedKeys(checks);
                setShow(1);




              }} style={{ background: "#ccc", borderColor: "#ccc" }}></Button>
              <Button type='primary' icon={<CheckOutlined />} onClick={async () => {
                if (data.newName) {
                  data.roleName = data.newName;
                }
                try {
                  console.log(data);

                  await addRoleRes(data);
                  getRoleList(page, limit);
                  message.success("更新成功");
                } catch (error) {
                  message.error("更新失败");
                }
              }} style={{ background: "#06f", borderColor: "#06f" }}></Button>


              <Button type='primary' icon={<EditOutlined />} onClick={() => {

                let list = [...roleList];
                list[index].flag = true;
                list[index].newName = data.roleName;
                setRoleList([...list])
                console.log(roleList);



              }}></Button>


              <Popconfirm
                title={`是否确认删除 角色 ${data.roleName} ？`}
                onConfirm={async () => {
                  try {
                    await deleteRoleRes(data.id);
                    getRoleList(page, limit);
                    message.success("删除成功")
                  } catch (error) {
                    message.error("删除失败")
                  }
                }}

                okText="确定"
                cancelText="取消"
              >
                <Button type='primary' danger icon={<DeleteOutlined />}></Button>
              </Popconfirm>

            </Space>
          </>
        )
      },
      width: 250,

    }
  ]



  const onExpand = (expandedKeysValue: React.Key[]) => {
    console.log('onExpand', expandedKeysValue);
    // if not set autoExpandParent to false, if children expanded, parent can not collapse.
    // or, you can remove all expanded children keys.
    setExpandedKeys(expandedKeysValue);
    setAutoExpandParent(false);
  };

  const onCheck = (checkedKeysValue: any) => {
    console.log('onCheck', checkedKeysValue);
    setCheckedKeys(checkedKeysValue);
  };



  const treeC = (
    <>
      <Input value={roleName} disabled></Input>
      <Tree
        checkable
        onExpand={onExpand}
        defaultExpandAll={true}//这个属性没效果
        expandedKeys={expandedKeys}//默认展开还得靠他
        autoExpandParent={autoExpandParent}
        onCheck={onCheck}
        checkedKeys={checkedKeys}
        treeData={treeData}
      />
      <Space>
      <Button type='primary' onClick={async()=>{
        let permissionId =checkedKeys.join(",") 
        
        try {
          await setRoleTreeRes(id,permissionId);
          message.success("设置成功")
          setShow(0);
        } catch (error) {
          message.error("设置失败")
        }
      }} >确定</Button>
      <Button type='default' onClick={()=>{setShow(0)}}>取消</Button>
      </Space>
      
    </>
  )


  return (
    <div>
      {show==0?<Card>
        {/* 查询 */}
        <Form layout='inline' style={{ marginBottom: 20 }} form={searchForm} >
          <Form.Item name="search">
            <Input ></Input>
          </Form.Item>
          <Form.Item>
            <Button type="primary" icon={<SearchOutlined />} onClick={() => {
              flag = true;
              setPage(1);
              getRoleList(1, limit)

            }}>查询</Button>
          </Form.Item>
          <Form.Item>
            <Button type="default" onClick={() => {
              flag = false;
              searchForm.resetFields();
              setPage(1);
              getRoleList(1, limit);
            }}>清空</Button>
          </Form.Item>
        </Form>

        {/* 添加 */}
        <Button type='primary' style={{ marginRight: 20 }} onClick={() => {
          setIsModalOpen(true);
        }}>添加</Button>
        <Button type="primary" danger onClick={() => { setIsOpen(true) }} disabled={!selectKeys.length}>批量删除</Button>
        {/* 批量删除对话框 */}
        <Modal title="批量删除" visible={isOpen} onOk={async () => {
          let arr: any = [];
          try {
            selectKeys.forEach(item => {
              arr.push(deleteRoleRes(item));
            })
            await Promise.all(arr);
            getRoleList(page, limit);
            message.success("删除成功")

          } catch (error) {
            message.error("删除失败")
          }
          setIsOpen(false);
        }} onCancel={() => { setIsOpen(false) }}>
          <h4>是否确认批量删除？</h4>
        </Modal>
        {/* 添加对话框 */}
        <Modal title="添加角色" visible={isModalOpen} onOk={() => {
          addForm.validateFields().then(async (value) => {
            try {
              await addRoleRes(addForm.getFieldsValue());
              setIsModalOpen(false);
              getRoleList(page, limit);
              addForm.resetFields();
              message.success("添加成功")
            } catch (error) {
              message.error("添加失败")
            }

          })


        }} onCancel={() => {
          setIsModalOpen(false);
          addForm.resetFields();
        }}>
          <Form layout='vertical' style={{ marginBottom: 20 }} form={addForm} >
            <Form.Item name="roleName" label="请输入新名称" rules={[{ required: true, message: "角色名不能为空" }]}>
              <Input ></Input>
            </Form.Item>
          </Form>
        </Modal>







        <Table dataSource={roleList} columns={columns} style={{ margin: "20px 0" }}
          bordered
          rowKey="id"
          rowSelection={{
            onChange: (checkedKeys: any, checkedList: any) => {
              console.log(checkedKeys);
              setSelectKeys(checkedKeys)

            }
          }}

          pagination={{
            total,
            current: page,
            pageSize: limit,
            pageSizeOptions: [3, 5, 7, 9],
            showQuickJumper: true,
            showSizeChanger: true,
            showTotal: (total) => {
              return `总共 ${total} 条`
            },
            onChange: (page, limit) => {
              setPage(page);
              setLimit(limit);
              getRoleList(page, limit)

            }

          }}
        >

        </Table>
      </Card>:
      <Card>
      {treeC}
    </Card>

      }
      


      
    </div>
  )
}
